﻿using Dm.filter.log;
using log4net;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PhysicalExamination5.Interface;
using PhysicalExamination5.Model;
using PhysicalExamination5.Service;
using PhysicalExamination5.WebApi.Utility.JWT;

namespace PhysicalExamination5.WebApi.Controllers
{
    /// <summary>
    /// 登录相关
    /// </summary>
    [ApiController]
    [ApiVersion("1.0")]
    [Route("[controller]/v{version:apiVersion}")]
    public class LoginController : Controller
    {
        private readonly ILogin _ILogin;
        private readonly ICustomJWTService _ICustomJWTService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private static readonly ILog log = LogManager.GetLogger(typeof(LoginController));

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ILogin"></param>
        /// <param name="ICustomJWTService"></param>
        /// <param name="httpContextAccessor"></param>
        public LoginController(ILogin ILogin, ICustomJWTService ICustomJWTService, IHttpContextAccessor httpContextAccessor)
        {
            _ILogin = ILogin;
            _ICustomJWTService = ICustomJWTService;
            _httpContextAccessor = httpContextAccessor;

            //配置日志ip地址参数信息
            string ipAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            log4net.GlobalContext.Properties["localIpAddress"] = ipAddress;
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public IActionResult GetInitialize()
        {
            log.Debug($@"API:{System.Reflection.MethodBase.GetCurrentMethod().Name}");
            string stripaddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            return Ok(_ILogin.Initialize(stripaddress));
        }
        /// <summary>
        /// 根据用户ID返回用户名和院区权限
        /// </summary>
        /// <param name="strstrUserId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public IActionResult SelUserDate(string strstrUserId)
        {
            log.Debug($@"API:{System.Reflection.MethodBase.GetCurrentMethod().Name}");
            return Ok(_ILogin.SelUserDate(strstrUserId));
        }
        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public IActionResult Login([FromBody] LoginClass login)
        {
            log.Debug($@"API:{System.Reflection.MethodBase.GetCurrentMethod().Name}");
            #region 声明变量

            int nret = 0;
            string strFanHuiZhi = "";
            string strToKen = "";
            string expiresTime = "";
            string strUserId = "";
            string strJueSeId = "";
            string strRefresh_Token = "";
            string strYuanQuQianZhui = "";
            string stripaddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

            #endregion

            nret = _ILogin.Login(out strFanHuiZhi,out strJueSeId, out strUserId, out strRefresh_Token,out strYuanQuQianZhui, login,stripaddress,login.strDengLuXiTong);
            if (nret != 0)
            {
                goto PROC_EXIT;
            }
            //获取token信息
            strToKen = _ICustomJWTService.funHuoQuToKen(login.strDengLuXiTong, strJueSeId, strUserId, login.strUserName, strYuanQuQianZhui, login.strYuanQu, 3000);
            expiresTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


        PROC_EXIT:
            return Ok(JsonConvert.SerializeObject(new ApiResult<object>()
            {
                Success = nret,
                Message = strFanHuiZhi,
                Data = new
                {
                    userInfo = new
                    {
                        userid = strUserId,
                        username = login.strUserName,
                        last_login_time = expiresTime,
                        token = strToKen,
                        refresh_token = strRefresh_Token,
                    }
                }
            }));
        }
        /// <summary>
        /// 根据UserId，refresh_token颁发token和refresh_token
        /// </summary>
        /// <param name="ToKenClass"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public IActionResult RefreshToken([FromBody] RefreshTokenClass ToKenClass)
        {
            log.Debug($@"API:{System.Reflection.MethodBase.GetCurrentMethod().Name}");
            #region 声明变量

            int nret = 0;
            string strFanHuiZhi = "";
            string strUserId = ToKenClass.strUserId;
            string strDengLuXiTong = "";
            string strJueSeId = "";
            string strUserName = "";
            string strYuanQuQianZhui = "";
            string strYuanQu = "";
            string strRefSalt = ToKenClass.strRefresh_Token;
            string strRefresh_Token = "";
            string strToKen = "";
            string stripaddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

            #endregion

            nret = _ILogin.RefreshToken(out strFanHuiZhi, out  strDengLuXiTong, out strJueSeId, out strUserName, out strYuanQuQianZhui,out strYuanQu, out strRefresh_Token, strUserId, strRefSalt, stripaddress);
            if (nret == 0)
            {
                strToKen = _ICustomJWTService.funHuoQuToKen(strDengLuXiTong, strJueSeId, strUserId, strUserName, strYuanQuQianZhui, strYuanQu, 30);
            }

            return Ok(JsonConvert.SerializeObject(new ApiResult<object>()
            {
                Success = nret,
                Message = strFanHuiZhi,
                Data = new
                {
                    token = strToKen,
                    refresh_token = strRefresh_Token
                }
            }));
        }
    }
}
